package utils

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"
)

//@author: heyibo
//@function: StructToMap
//@description: 利用反射将结构体转化为map
//@param: obj interface{}
//@return: map[string]interface{}

func StructToMap(obj interface{}) map[string]interface{} {
	obj1 := reflect.TypeOf(obj)
	obj2 := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < obj1.NumField(); i++ {
		data[obj1.Field(i).Name] = obj2.Field(i).Interface()
	}
	return data
}

//@author: heyibo
//@function: ArrayToString
//@description: 将数组格式化为字符串
//@param: array []interface{}
//@return: string

func ArrayToString(array []interface{}) string {
	return strings.Replace(strings.Trim(fmt.Sprint(array), "[]"), " ", ",", -1)
}

//@author: heyibo
//@function: StringToInt
//@description: 将字符串转化成int
//@param: e string
//@return: int,error
func StringToInt(e string) (int, error) {
	return strconv.Atoi(e)
}

//@author: heyibo
//@function: GetCurrentTimeStr
//@description: 获取当前格式化的时间
//@param:
//@return: string
func GetCurrentTimeStr() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

//@author: heyibo
//@function: GetCurrentTime
//@description: 获取当前时间
//@param:
//@return: time
func GetCurrentTime() time.Time {
	return time.Now()
}

//@author: heyibo
//@function: StructToJsonStr
//@description: 将结构体转化为str
//@param: e interface{}
//@return: string
func StructToJsonStr(e interface{}) (string, error) {
	if b, err := json.Marshal(e); err == nil {
		return string(b), err
	} else {
		return "", err
	}
}
